class ItemsController < ApplicationController
  before_filter :find_item,     :only => [:show,    :edit, :update, :destroy]
  before_filter :require_login, :only => [:create,  :update]
  
  def index
  end
  
  def show
  end
  
  def new
    @item = Item.new
  end
  
  def create
    @gallery = Gallery.find(params[:gallery_id]) if params[:gallery_id]
    #params[:item][:item_options_ids] ||= []
    @item = Item.new(params[:item])
    (@item.gallery = @gallery) if params[:gallery_id]
    @item.price_list = @gallery.price_list
    @item.user = current_user
    @item.save!
    if params[:render]
      (@video = Video.find(params[:item][:video_id])) if params[:item][:video_id]
      (@photo = Photo.find(params[:item][:photo_id])) if params[:item][:photo_id]
      render :partial => "conditional_add_to_cart"
      return
    end
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Couldn't add that item to your cart. Try again..."
    redirect_to :back
  end
  
  def edit    
  end
  
  def update
    @gallery = Gallery.find(params[:gallery_id]) if params[:gallery_id]
    params[:item][:item_options_ids] ||= []
    @item.user = current_user
    @item.update_attributes!(params[:item])
    flash[:update] = 'Information for that item has been updated'      
    redirect_to user_orders_url
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Something went wrong and the item couldn't be updated."
    redirect_to :back
  end

  def destroy
    @item.destroy
    flash[:update] = 'The item has been removed'      
    redirect_to orders_url
  end

protected
  def find_item
    @item = Item.find(params[:id])
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that.'
      redirect_to login_url
    end
  end
end
